import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { FetchService } from '../../../core/net/fetch.service';
import { NzMessageService } from 'ng-zorro-antd';
import { Router } from '@angular/router';
import { isToday, format, subDays } from 'date-fns';
import { UploadChangeParam, UploadFile } from 'ng-zorro-antd/upload';
import * as moment from 'moment';

@Component({
    selector: 'app-water-record',
    templateUrl: './water-record.component.html',
    styleUrls: ['./water-record.component.scss']
})
export class WaterRecordComponent implements OnInit {
    searchForm: FormGroup;
    manageId = JSON.parse(localStorage.userInfo).manageId;
    tableData = [];
    total: number;
    pageNum = 1;
    pageSize = 50;
    loading = true;
    form: FormGroup;
    modalShow: boolean = false;
    modalTitle = '';
    peopleOption;
    selectedDay;
    dayList = [];

    uploadFileIds = [];
    uploadUrl = `${(window as any).environment.apiBaseUrl}comm/file/upload`;
    fileList: UploadFile[] = [];

    constructor(private fb: FormBuilder,
                private fetchService: FetchService,
                private router: Router,
                private message: NzMessageService) {
        this.searchForm = this.fb.group({
            keyword: [null],
            rangePickerTime: [[]],
            fromMember: [null],
            toMember: [null]
        });

        this.form = this.fb.group({
            id: [null],
            changeDate: [null],
            content: [null],
            fromMember: [null],
            toMember: [null],
            advice: [null]
        });
    }

    ngOnInit(): void {
        this.getPeopleOption();
        this.getDayList();
    }

    queryInfo(reset: boolean = false): void {
        if (reset) {
            this.pageNum = 1;
        }
        const stDate = this.searchForm.value.rangePickerTime[0] ? format(this.searchForm.value.rangePickerTime[0], 'YYYY-MM-DD') : '';
        const edDate = this.searchForm.value.rangePickerTime[1] ? format(this.searchForm.value.rangePickerTime[1], 'YYYY-MM-DD') : '';
        const param = {
            orderByField: 'changeDate',
            orderBy: 'desc',
            pageNum: this.pageNum,
            pageSize: this.pageSize,
            content: this.searchForm.value.keyword,
            manageId: JSON.parse(localStorage.userInfo).manageId,
            fromMember: this.searchForm.value.fromMember,
            toMember: this.searchForm.value.toMember,
            stDate: this.selectedDay,
            edDate: this.selectedDay
        };
        this.fetchService.post<any>('schedule/wrsWorkHistory/list', param).subscribe(res => {

            this.tableData = res.list.map(item => {
                return { ...item, ...{ expand: true } };
            });
        });
    }

    getPeopleOption(): void {
        this.fetchService.post<any>('sys/sysApiInfo/queryApiData', { manageId: this.manageId, apicode: '15' })
            .subscribe(res => {
                this.peopleOption = res;
                this.peopleOption.unshift({ name: '请选择', id: '' });
            });
    }

    onConfirm(): void {
        if (!this.form.valid) {
            this.message.warning('信息填写有误');
            return;
        }
        this.uploadFileIds = [];
        this.fileList.map(file => {
            this.uploadFileIds.push(file.response.data.id);
        });
        const param: any = {
            manageId: JSON.parse(localStorage.userInfo).manageId,
            changeDate: format(this.form.value.changeDate, 'YYYY-MM-DD HH:mm:ss'),
            content: this.form.value.content,
            toMember: this.form.value.toMember,
            fileIds: this.uploadFileIds.join(',')
        };

        this.fetchService.post('schedule/wrsWorkHistory/add', param).subscribe(res => {
            this.message.success('操作成功！');
            this.modalShow = false;
            this.queryInfo();
        });
    }

    onAdd(): void {
        this.modalTitle = '新增调度日志';
        this.form.reset();
        this.modalShow = true;
    }

    onCancel() {
        this.modalShow = false;
    }

    onDelete(id): void {
        this.fetchService.get(`schedule/wrsWorkHistory/remove/${id}`).subscribe(res => {
            this.message.info('删除成功');
            this.queryInfo();
        });
    }

    getDayList(): void {
        const stDate = this.searchForm.value.rangePickerTime[0] ? format(this.searchForm.value.rangePickerTime[0], 'YYYY-MM-DD') : '';
        const edDate = this.searchForm.value.rangePickerTime[1] ? format(this.searchForm.value.rangePickerTime[1], 'YYYY-MM-DD') : '';
        const param = {
            stDate: stDate,
            edDate: edDate,
            keyword: this.searchForm.value.keyword
        };
        this.fetchService.post<any>('schedule/wrsWorkHistory/dateList', param).subscribe(res => {
            this.dayList = res.map(item => {
                return {
                    text: format(item, 'MM月DD日'),
                    value: item
                };
            });
            this.selectDay(this.dayList[0]);
        });
    }

    // 选择右侧日期
    selectDay(data): void {
        this.selectedDay = data.value;
        this.queryInfo();
    }

    download(file): void {
        this.fetchService.export(`comm/file/down/${file.id}`, {
            responseType: 'blob'
        }).subscribe(data => {
            const fileBlob = new Blob([data], { type: 'charset=utf-8' });
            const link = document.createElement('a');
            link.id = 'waterRecodeDownloadId';
            document.body.appendChild(link);
            link.style.display = 'none';
            link.download = file.fileName;
            link.href = URL.createObjectURL(fileBlob);
            link.click();
            const tempA = document.getElementById('waterRecodeDownloadId');
            if (tempA) {
                tempA.parentNode.removeChild(tempA);
            }
        });
    }

    exportDocx(): void {
        let params;
        if (!this.searchForm.value.rangePickerTime[0]) {
            params = {
                stDate: this.dayList[0].value,
                edDate: this.dayList[0].value,
                manageId: JSON.parse(localStorage.userInfo).manageId
            };
        } else {
            params = {
                stDate: moment(this.searchForm.value.rangePickerTime[0]).format('YYYY-MM-DD'),
                edDate: moment(this.searchForm.value.rangePickerTime[1]).format('YYYY-MM-DD'),
                manageId: JSON.parse(localStorage.userInfo).manageId
            };
        }
        this.fetchService.export(`comm/word/exportWord`, {
            wordMapper: 'WordMapper-WrsWorkHistory',
            queryParams: JSON.stringify(params),
            targetFileName: '水量调度记录.docx'
        }).subscribe(data => {
            const fileBlob = new Blob([data], { type: 'charset=utf-8' });
            const link = document.createElement('a');
            link.id = 'waterRecodeDownloadId';
            document.body.appendChild(link);
            link.style.display = 'none';
            link.download = '水量调度记录.docx';
            link.href = URL.createObjectURL(fileBlob);
            link.click();
            const tempA = document.getElementById('waterRecodeDownloadId');
            if (tempA) {
                tempA.parentNode.removeChild(tempA);
            }
        });
    }
}
